package util;

import entity.Student;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author zhu
 * @date 2024-03-27
 */
public class BeanUtil {
    public static void setProperty(Object bean,String propertyName,Object value) throws Exception{
        Class<?> clazz = bean.getClass();
        Field field = clazz.getDeclaredField(propertyName);
        Class<?> fieldType = field.getType();
        String setField = "set" + field.getName().toUpperCase().charAt(0) + field.getName().substring(1);
        Method set = clazz.getMethod(setField,fieldType);
        set.invoke(bean,value);
    }

    public static Object getProperty(Object bean,String propertyName) throws Exception {
        Class<?> clazz = bean.getClass();
        Field field = clazz.getDeclaredField(propertyName);
        String getField = "get" + field.getName().toUpperCase().charAt(0) + field.getName().substring(1);
        Method get = clazz.getMethod(getField);
        String str = (String) get.invoke(bean);
        return str;
    }

    public static void copyProperties(Object source,Object target) throws Exception {
        Class<?> clazz1 = source.getClass();
        Class<?> clazz2 = target.getClass();
        if (clazz1 == clazz2){
            Field[] field1 = clazz1.getDeclaredFields();
            for (Field field : field1){     // name
                field.setAccessible(true);
                String getField = "get" + field.getName().toUpperCase().charAt(0) + field.getName().substring(1);
                Method get = clazz1.getMethod(getField);
                Object s = get.invoke(source);  // String

                Field field2 = clazz2.getDeclaredField(field.getName());
                field2.setAccessible(true);
                Class<?> type = field2.getType();
                String setField = "set" + field2.getName().toUpperCase().charAt(0) + field2.getName().substring(1);
                Method set = clazz2.getMethod(setField,type);
                set.invoke(target,s);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Student stu1 = new Student("zs",18,50D);
        Student stu2 = new Student();
        BeanUtil.copyProperties(stu1,stu2);
        System.out.println(stu2.getName() + " " + stu2.getAge() + " " + stu2.getWeight());
    }
}
